package com.muqi.app.qlearn.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.adapter.CommentAdapter;
import com.muqi.app.qlearn.modles.CommentBean;
import com.muqi.app.qlearn.modles.NoticeBean;
import com.muqi.app.qlearn.student.BaseSpeechActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.widget.pulltorefresh.XListView;

public class NoticeDetailsActivity extends BaseSpeechActivity implements
		XListView.IXListViewListener, OnItemClickListener, OnClickListener {
	public static final String NOTICE_MSG_ID = "notice_msg_id";
	public static final String NOTICE_MSG_INFOS = "notice_msg_infos";
	private XListView mListview;
	private EditText contentEdt;
	private View headerView;
	private TextView nceTitle;
	private TextView nceInfos;
	private TextView nceContent;
	private LinearLayout confirmLayout;
	private LinearLayout cfmWithFlower;
	private LinearLayout confirmButton;

	private List<CommentBean> commentlist = new ArrayList<CommentBean>();
	private CommentAdapter mAdapter = null;
	private int page = 1;

	private String notice_id;
	private NoticeBean noticeInfo = null;

	private String reply_user_id = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		notice_id = getIntent().getStringExtra(NOTICE_MSG_ID);
		if (notice_id == null || TextUtils.isEmpty(notice_id)) {
			finish();
		}
		noticeInfo = (NoticeBean) getIntent().getSerializableExtra(
				NOTICE_MSG_INFOS);
		setContentView(R.layout.aty_homework_details);
	}

	@SuppressLint("InflateParams")
	@Override
	protected void onInit() {
		TextView mTitle = (TextView) findViewById(R.id.detail_title);
		mTitle.setText("通知收阅");
		mListview = (XListView) findViewById(R.id.xListView);
		mListview.setXListViewListener(this);
		mListview.setPullLoadEnable(false);
		mListview.setPullRefreshEnable(false);
		mListview.setOnItemClickListener(this);
		contentEdt = (EditText) findViewById(R.id.contentEditText);

		headerView = LayoutInflater.from(this).inflate(
				R.layout.header_notice_details, null);
		nceTitle = (TextView) headerView.findViewById(R.id.notice_title);
		nceInfos = (TextView) headerView.findViewById(R.id.notice_infos);
		nceContent = (TextView) headerView.findViewById(R.id.notice_content);
		confirmLayout = (LinearLayout) headerView
				.findViewById(R.id.confirmLayout);
		cfmWithFlower = (LinearLayout) headerView
				.findViewById(R.id.confirmWithFlower);
		cfmWithFlower.setOnClickListener(this);
		confirmButton = (LinearLayout) headerView
				.findViewById(R.id.confirmReceived);
		confirmButton.setOnClickListener(this);

		mListview.addHeaderView(headerView, null, false);
		mListview.setAdapter(null);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirmWithFlower:
			cfmWithFlower.setEnabled(false);
			confirmButton.setEnabled(false);
			confirmingNotice(1);
			break;
		case R.id.confirmReceived:
			cfmWithFlower.setEnabled(false);
			confirmButton.setEnabled(false);
			confirmingNotice(0);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onData() {
		super.onData();
		showLoading();
		if (noticeInfo != null) {
			showNoticeContentView(noticeInfo);
		} else {
			loadingNoticeDetails();
		}
		loadingDetailComments();
	}

	private void showNoticeContentView(NoticeBean notice) {
		if (notice.title == null && notice.content == null) {
			ShowToast.showShort(mContext, "该消息已经被删除无法查看");
			finish();
		}
		nceTitle.setText(notice.title + "");
		nceInfos.setText(notice.name + "  " + notice.create_time);
		nceContent.setText(notice.content + "");
		if (notice.read_st.equals("n")) {
			confirmLayout.setVisibility(View.VISIBLE);
		}
	}

	public void onBack(View v) {
		this.finish();
	}

	private void loadingNoticeDetails() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			sendMap.put("message_id", notice_id);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_NOTICE_DETAILS_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						NoticeBean getDetails = ResponseUtils.getNoticeDetails(
								mContext, result);
						if (getDetails != null)
							noticeInfo=getDetails;
							showNoticeContentView(getDetails);
					} else {
						 showToast(result);
						  Intent intent=new Intent();
						  intent.putExtra("isDelete", true);
						  setResult(RESULT_OK, intent);
						  finish();
						
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void confirmingNotice(final int flowerCount) {
		if(noticeInfo!=null){
			if (NetWorkUtils.isNetworkAvailable(this)) {
				HashMap<String, Object> sendMap = new HashMap<String, Object>();
				sendMap.put("token", mSpUtil.getToken());
				sendMap.put("student_id", mSpUtil.getCurrentChildId());
				sendMap.put("message_id", notice_id);
				sendMap.put("flowercount", flowerCount);
				String requestUrl = ParamsUtils.buildParams(
						NetWorkApi.CONFIRM_NOTICE_MESSAGE_API, sendMap);
				MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

					@Override
					public void onAsyncCallBack(RESULTCODE resuleCode,
							String request, String result) {
						if (resuleCode == RESULTCODE.SUCCESS) {
							
							confirmLayout.setVisibility(View.GONE);
							if (noticeInfo.read_st != null) {
								noticeInfo.read_st = "y";
							}
							if (flowerCount == 1) {
								cfmWithFlower.setEnabled(true);
								noticeInfo.flower_count = (Integer
										.parseInt(noticeInfo.flower_count) + 1)
										+ "";
								showToast("确认并送花成功");
							}else{
								showToast("已确认");
							}
							Intent intent = new Intent();
							intent.putExtra("bean", noticeInfo);
							setResult(RESULT_OK, intent);
						}
					}
				});

			} else {
				ShowToast.showShort(this, R.string.net_break);// 提示无网络
			}
		}
		
	}

	private void loadingDetailComments() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("id", notice_id);
			sendMap.put("type", "message");// 'class_job','goods','socially_activity','message'
			sendMap.put("page", page);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_HOMEWORK_COMMENTLISTS_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					onLoadView();
					hideLoading();
					if (resuleCode == RESULTCODE.SUCCESS) {
						List<CommentBean> getLists = ResponseUtils
								.getUserComments(mContext, result);
						if (getLists != null && getLists.size() > 0) {
							if (page == 1) {
								commentlist.clear();
								commentlist = getLists;
								if (mAdapter != null)
									mAdapter = null;
								mAdapter = new CommentAdapter(mContext,
										commentlist);
								mAdapter.setHome(true);
								mListview.setAdapter(mAdapter);
							} else {
								for (CommentBean item : getLists) {
									commentlist.add(item);
								}
								mAdapter.notifyDataSetChanged();
							}
							if (getLists.size() < 10) {
								mListview.setPullLoadEnable(false);
							} else {
								mListview.setPullLoadEnable(true);
								page++;
							}
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void onLoadView() {
		mListview.stopRefresh();
		mListview.stopLoadMore();
		mListview.setRefreshTime("刚刚");
	}

	public void openVoice2Words(View v) {
		startSpeech();
	}

	@Override
	protected void onSpeech2Words(String speechWords) {
		contentEdt.setText(speechWords);
		contentEdt.setSelection(contentEdt.length());
	}

	public void sendMyCreditMsg(View v) {
		String mContent = contentEdt.getText().toString();
		if (TextUtils.isEmpty(mContent)) {
			showToast("评论内容不能为空哦");
		} else {
			publiMyCommentInfo(reply_user_id, mContent);
			contentEdt.setText("");
			contentEdt.setHint("评论...");
			reply_user_id = "";
			dismissSoftKeyboard();
		}
	}

	private void publiMyCommentInfo(String replyUser, String content) {
		if (noticeInfo != null) {
			if (NetWorkUtils.isNetworkAvailable(this)) {
				HashMap<String, Object> sendMap = new HashMap<String, Object>();
				sendMap.put("token", mSpUtil.getToken());
				sendMap.put("obj_type", "message");
				sendMap.put("obj_id", notice_id);
				sendMap.put("reply_to_user_id", replyUser);
				sendMap.put("rating", 5);
				sendMap.put("content", content);
				String requestUrl = ParamsUtils.buildParams(
						NetWorkApi.ADD_MYCOMMENT_TO_USER_API, sendMap);
				MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

					@Override
					public void onAsyncCallBack(RESULTCODE resuleCode,
							String request, String result) {
						if (resuleCode == RESULTCODE.SUCCESS) {
							noticeInfo.commentCount = (Integer
									.parseInt(noticeInfo.commentCount) + 1)
									+ "";
							Intent intent = new Intent();
							intent.putExtra("bean", noticeInfo);
							setResult(RESULT_OK, intent);
							onRefresh();
						}
					}
				});
			} else {
				ShowToast.showShort(this, R.string.net_break);// 提示无网络
			}
		} else {
			showToast("该记录已被删除，无法评论");
		}

	}

	@Override
	public void onRefresh() {
		page = 1;
		loadingDetailComments();
	}

	@Override
	public void onLoadMore() {
		loadingDetailComments();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (commentlist.get(position - 2).author_userInfo.id.equals(mSpUtil
				.getUserId())) {
			return;
		}
		reply_user_id = commentlist.get(position - 2).author_userInfo.id;
		contentEdt.setHint("回复:"
				+ commentlist.get(position - 2).author_userInfo.name);
		getSoftInput(contentEdt);
	}
}
